import 'package:flustars/flustars.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:provider/provider.dart';

class CollapseRowItemData {
  String title;
  String desc;
  Function? onTap;

  CollapseRowItemData({
    this.title = '',
    this.desc = '',
    this.onTap,
  });
}

class CollapseRowData {
  String title;
  List<CollapseRowItemData> list;

  CollapseRowData({
    this.title = '',
    this.list = const [],
  });
}

class CollapseRow extends StatefulWidget {
  final MaterialColor color;
  final CollapseRowData? data;

  CollapseRow({
    this.color = Colors.blue,
    this.data,
  });

  @override
  _CollapseRowState createState() => _CollapseRowState();
}

class _CollapseRowState extends State<CollapseRow>
    with SingleTickerProviderStateMixin, AutomaticKeepAliveClientMixin {
  late CollapseRowData _data;

  Color _lightColor = Colors.blue[300]!;

  GlobalKey _listKey = GlobalKey();

  double _currentHeight = 0.0;

  double _originHeight = 0.0;

  late BorderSide _borderSide;

  Duration _duration = Duration(milliseconds: 200);

  Curve _curve = Curves.easeIn;

  final Tween<double> _turnsTween = Tween<double>(
    begin: 1,
    end: 1.5,
  );

  late AnimationController _controller;

  late Animation<double> _turnsAnimation;

  void _handleToggle() {
    setState(() {
      if (_currentHeight > 0) {
        _currentHeight = 0;
        _controller.reverse();
      } else {
        _currentHeight = _originHeight;
        _controller.forward();
      }
    });
  }

  @override
  void initState() {
    super.initState();

    _data = widget.data ?? CollapseRowData();

    if (widget.color[300] != null) {
      _lightColor = widget.color[300] as Color;
    }

    _borderSide = BorderSide(
      color: _lightColor,
      width: 0.3,
    );

    _controller = AnimationController(
      vsync: this,
      duration: _duration,
    );

    _turnsAnimation = _turnsTween
        .animate(CurvedAnimation(parent: _controller, curve: _curve));

    WidgetsBinding.instance!.addPostFrameCallback((_) {
      _originHeight =
          WidgetUtil.getWidgetBounds(_listKey.currentContext!).height;
    });
  }

  @override
  bool get wantKeepAlive => true;

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: _handleToggle,
      child: Container(
        padding: EdgeInsets.symmetric(
          vertical: 10,
          horizontal: 15,
        ),
        decoration: BoxDecoration(
          color: widget.color,
          border: _currentHeight > 0
              ? Border(
                  top: _borderSide,
                  bottom: _borderSide,
                )
              : Border(),
        ),
        child: Column(
          children: [
            Padding(
              padding: EdgeInsets.symmetric(vertical: 10),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                crossAxisAlignment: CrossAxisAlignment.center,
                children: [
                  Expanded(
                    flex: 1,
                    child: Text(
                      _data.title,
                      style: TextStyle(
                        color: Colors.white,
                        fontSize: 16,
                        height: 1,
                      ),
                    ),
                  ),
                  SizedBox(width: 40),
                  RotationTransition(
                    turns: _turnsAnimation,
                    child: Icon(
                      Icons.keyboard_arrow_down_outlined,
                      color: Colors.white,
                    ),
                  ),
                ],
              ),
            ),
            AnimatedContainer(
              height: _currentHeight,
              duration: _duration,
              curve: _curve,
              child: SingleChildScrollView(
                reverse: true,
                physics: NeverScrollableScrollPhysics(),
                // 隐藏了的列表
                child: Container(
                  key: _listKey,
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.stretch,
                    children: [
                      SizedBox(height: 5),
                      ...List.generate(
                        _data.list.length,
                        (index) {
                          CollapseRowItemData data = _data.list[index];
                          return Container(
                            margin: index < _data.list.length - 1
                                ? EdgeInsets.only(bottom: 15)
                                : EdgeInsets.zero,
                            child: CollapseRowItem(
                              data: data,
                              color: _lightColor,
                            ),
                          );
                        },
                      ),
                    ],
                  ),
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }
}

class CollapseRowItem extends StatelessWidget {
  final CollapseRowItemData data;
  final Color color;

  CollapseRowItem({
    required this.data,
    required this.color,
  });

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: () {
        if (data.onTap != null) {
          data.onTap!();
        }
      },
      child: Container(
        padding: EdgeInsets.symmetric(vertical: 10, horizontal: 15),
        decoration: BoxDecoration(
            color: color, borderRadius: BorderRadius.circular(15)),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text(
              data.title,
              style: TextStyle(
                color: Colors.white,
                fontSize: 22,
              ),
            ),
            SizedBox(height: 10),
            Text(
              data.desc,
              style: TextStyle(
                color: Colors.white,
                fontSize: 12,
              ),
            ),
          ],
        ),
      ),
    );
  }
}
